//
//  MWSearchResultController.m
//  XiRan-iOS
//
//  Created by liuyiming on 2019/11/24.
//  Copyright © 2019 Wood. All rights reserved.
//

#import "MWHomeSearchResultController.h"
#import "MWGoodsDetailsController.h"
#import "MWGoodsCell.h"

@interface MWHomeSearchResultController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property(strong, nonatomic) UICollectionView *collectionView;
@property(strong, nonatomic) NSMutableArray *goodsArray;

@property(nonatomic, strong) NSString *keyword;
@property(nonatomic, assign) NSInteger page;
@property(nonatomic, assign) NSInteger size;
@property(nonatomic, assign) MWRequestMode requestMode;

@property(nonatomic, assign) CGFloat cellHeight;

@end

@implementation MWHomeSearchResultController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _page = 1;
    _size = 10;
    _requestMode = MWRequestModeRefresh;
    
    [self setupPageSubviews];
}

- (void)searchWithKeyword:(NSString *)keyword {
    _keyword = keyword;
    [self.goodsArray removeAllObjects];
    [self refreshSearch];
}

- (void)clearSearchResult {
    [self.goodsArray removeAllObjects];
    [_collectionView reloadData];
}

#pragma mark - 刷新数据
- (void)refreshSearch {
    _page = 1;
    _requestMode = MWRequestModeRefresh;
    [self searchWithKeyword:_keyword page:_page size:_size];
}

#pragma mark - 加载更多数据
- (void)loadMoreSearch  {
    _page++;
    _requestMode = MWRequestModeLoadMore;
    [self searchWithKeyword:_keyword page:_page size:_size];
}

#pragma mark - 搜索
- (void)searchWithKeyword:(NSString *)keyword page:(NSInteger)page size:(NSInteger)size {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.label.text = [[MWConfigManager manager] objectForKey:@"loadin" defaultValue:@"加载中..."];
    
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:[MWUserManager manager].user.token forKey:@"token"];
    [paraDic setObject:keyword forKey:@"field"];
    [paraDic setObject:[NSString stringWithFormat:@"%ld", (long)page] forKey:@"page"];
    [paraDic setObject:[NSString stringWithFormat:@"%ld", (long)size] forKey:@"size"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];

    MWWeakSelf
    
    NSString *searchUrl = nil;
    if (self.showroom && self.showroom.length) {
        paraDic[@"gallery"] = self.showroom;
        searchUrl = Gallery_search_url;
    } else {
        searchUrl = kSearchUrl;
    }
    [[MWNetworkManager manager] POST:searchUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
//        NSString *msg = [dic objectForKey:@"msg"];
        if (code == 1) {
            NSArray *tempArray = [MWGoods mj_objectArrayWithKeyValuesArray:[dic objectForKey:@"data"]];
            if (weakSelf.requestMode == MWRequestModeRefresh) {
                [self.goodsArray removeAllObjects];
                if (tempArray.count == weakSelf.size) {
                    weakSelf.collectionView.mj_footer.hidden = NO;
                }
                
            } else {
                if (tempArray.count < weakSelf.size) {
                    [weakSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
                } else {
                    [weakSelf.collectionView.mj_footer endRefreshing];
                }
            }
            
            [self.goodsArray addObjectsFromArray:tempArray];
            self.cellHeight = [self calculateCellHeight];
            [self.collectionView reloadData];
        }
        [hud hideAnimated:YES];
    } failure:^(NSError *error) {
        [hud hideAnimated:YES];
    }];
}

#pragma mark - UICollectionViewDataSource && UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if ([MWConfigManager manager].isNetError) {
        self.view.hidden = YES;
    } else if (!self.goodsArray.count) {
        if (self.isFirst) {
            
        } else {
            self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"nodata" defaultValue:@"暂无数据"];
            self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
            collectionView.hidden = YES;
            self.view.hidden = NO;
        }
    } else {
        self.errorTitleLabel.hidden = self.errorImageView.hidden = YES;
        collectionView.hidden = NO;
        self.view.hidden = NO;
    }
    return self.goodsArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"MWGoodsCell";
    MWGoodsCell *goodCell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    [goodCell setupData:self.goodsArray[indexPath.row]];
    return goodCell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    MWGoods *goods = self.goodsArray[indexPath.row];
    MWGoodsDetailsController *controller = [[MWGoodsDetailsController alloc] init];
    controller.productId = [NSString stringWithFormat:@"%ld", goods.mid];
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 11;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 15;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(16, 16, 0, 16);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((kScreenWidth - 47) / 2, _cellHeight);
}

#pragma mark - 计算cell 高度
- (CGFloat)calculateCellHeight {
    CGFloat imgH = 120.0f;
    CGFloat titleH = 22.0f;
    CGFloat priceH = 0;
    CGFloat attrH = 0.0f;
    
    for (MWGoods *goods in self.goodsArray) {
        if (!goods.shuxing) {
            break;
        }
        
        if (goods.price) {
            priceH = 22.0f;
        }
        
        if (attrH < goods.shuxing.count * 22) {
            attrH = goods.shuxing.count * 22;
        }
    }
    
    return imgH + 8 + titleH + priceH + attrH;
}



#pragma mark - Setter && Getter
- (NSMutableArray *)goodsArray {
    if (!_goodsArray) {
        _goodsArray = [[NSMutableArray alloc] init];
    }
    return _goodsArray;
}

#pragma mark - UI
- (void)setupPageSubviews {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [_collectionView registerClass:[MWGoodsCell class] forCellWithReuseIdentifier:@"MWGoodsCell"];
    [self.view addSubview:_collectionView];
   
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    MJRefreshBackNormalFooter *refreshFooter = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreSearch];
    }];
    refreshFooter.stateLabel.hidden = YES;
    _collectionView.mj_footer.hidden = YES;
    _collectionView.mj_footer = refreshFooter;
}

@end
